<?php
require_once('./modules/feeds/feedItem.inc');
require_once('./modules/cache.inc');
require_once('./modules/util.inc');
require_once('./modules/blog/blogpost.inc');
require_once('./modules/blog/blogComment.inc');
require_once("./modules/ext/recaptcha/recaptchalib.php");
require_once("./modules/ext/securimage/securimage.php");

class PostRenderer extends Renderer
{
	private $_post;
	private $_postComments;
	private $_message;
	
	function pageLoad()
	{
		$this->getBlogPost(Util::safeGetPost('postId'));

		switch( $this->action )
		{
			case "add_comment":
				$this->addComment();
				break;
			case "del_comment":
				$this->delComment();
				break;
			case "del_post":
				$this->delPost();
				break;
			case "success";
				$this->message = "Comment added successfully";
				break;
			case "":
			case "show":
			default:
				break;
		}
	}
	
	private function delPost()
	{
		global $G_HOME;
		
		if ( !isset($this->user) || $this->user->type < 1)
		{
			$this->message = "You are not permitted to delete this post";
			return;
		}
		
		if( $this->_post->delete())
		{
			$cacheId = "post-id-".$postId;
			$cache = new Cache();
			$cache->revoke($cacheId);
			header("location: ".$G_HOME);
		}
		else
		{
			$this->message = "Post could not be deleted";
		}
	}
	
	private function delComment()
	{
		if ( !isset($this->user) || $this->user->type < 1)
		{
			$this->message = "You are not permitted to delete comments";
			return;
		}

		$commentId = Util::safeGetPost('commentId');
		
		if(!BlogComment::delete($commentId))
		{
			$this->message = "Failed to delete comment";
		}
		else
		{
			$postId = Util::safeGetPost('postId');
			//revoking the cached file, so comment will disapear.
			$cacheId = "post-id-".$postId;
			$cache = new Cache();
			$cache->revoke($cacheId);

			$this->message = "Comment deleted successfully";
			$this->action = "success";
		}
	}
	
	private function addComment()
	{
		$postId = Util::safeGetPost('postId');

		$captchaSuccess = true;
		
		if($this->config->get('./useRecaptcha') == '1')
		{
			$resp = recaptcha_check_answer ("6LdVzgYAAAAAAAW6-LIzpEry1EdVAJ9OvCuIAsKY",
									$_SERVER["REMOTE_ADDR"],
									$_POST["recaptcha_challenge_field"],
									$_POST["recaptcha_response_field"]);
			
			if (!$resp->is_valid) 
				$captchaSuccess = false;
		}
		else
		{
			$captcha = new Securimage();
			if($captcha->check(Util::safeGetPost('txtCaptcha')) == false)
				$captchaSuccess = false;
		}
		
		if(!$captchaSuccess)
		{
			$this->_message = "Wrong image text, please try again";
			return;
		}

		$comment = trim(Util::safeGetPost('txtComment'));
		
		if(!isset($comment) || $comment == false || strlen($comment) == 0)
		{
			$this->_message = "Empty comment submitted";
			return;
		}
		
		$email = trim(Util::safeGetPost('txtEmail'));
		
		if(strlen($email)>0 && !Util::isEmail($email))
		{
			$this->_message = "Please provide a valid email, or leave empty";
			return;
		}
		
		if(!BlogComment::add($postId,$comment,$email))
		{
			$this->_message = "Failed to add comment, please try again later";
			return;
		}
		
		//revoking the cached file, so new comment apears.
		$cacheId = "post-id-".$postId;		
		$cache = new Cache();
		$cache->revoke($cacheId);
		
		$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$url=preg_replace("/\?.*/","",$url)."?act=success";
		header("Location: ".$url);
	}
	
	private function getBlogPost($postId)
	{
		global $G_HOME;
		
		$post;
		
		//name the content type, with paging
		$cacheId = "post-id-".$postId;

		$cacheStatus = 'DEAD';
		
		$cache = new Cache();
		
		if( !$cache->ERROR )
			$cacheStatus = $cache->check_cache($cacheId);
		
		if($cacheStatus == 'HIT')
		{
			$arr = $cache->get($cacheId);
			$this->_post = $arr[0];
			$this->_postComments = $arr[1];
			
			if ($this->_post->deleted)
			{
				header("Status: 301");
				header("Location: ".$G_HOME);
			}
		}
		else
		{
			$this->_post = new BlogPost();
			
			if( !$this->_post->load($postId) )
			{
				header("Location: ".$G_HOME."?pg=404");
				die();
			}

			if ($this->_post->deleted)
			{
				header("Status: 301");
				header("Location: ".$G_HOME);
			}

			$this->_postComments = BlogComment::getByPost($this->_post->id);

			$arr = Array();
			$arr[] = $this->_post;
			$arr[] = $this->_postComments;
			
			$cache->set($cacheId,$arr);
		}
		
		$this->_post->promoteViewCount();
	}

	function renderContent()
	{
		global $G_HOME;
		global $content;
		
		$content .=
		"<script src='".Util::combinePath($G_HOME,"/script/popup.js")."'></script>
		<script lang='javascript'>
			function askDelPost()
			{
				_popup.show('Should id delete this post?',delPost);
			}
			function delPost()
			{
				document.location.href='".Util::combinePath($G_HOME,"index.php?pg=view_post&act=del_post&postId=".$this->_post->id)."'
			}
		</script>";
		$content .= 
		"<div>
			<h2 class='postTitle'>".$this->_post->title."</h2>
			<h5 class='postTime'>".date('d/m/y H:i',$this->_post->creationDate)."</h5>
		</div>";

		$content .= "<p><div class='postContent' style='line-height:1.5em;'>".$this->_post->content."</div></p>";
		$content .= "<p><h5 class='postCommentCount'>Viewed: ".$this->_post->viewCount.", Comments: ".$this->_post->commentCount."</h5></p>";
		if ( isset($this->user) && $this->user->type >= 1)
			$content .= "<p><a href='".Util::combinePath($G_HOME,"index.php?pg=edit_post&postId=".$this->_post->id)."'>Edit this post</a>
			or <a href='javascript:void 0;' onclick='askDelPost();'>Delete it</a></p>";
		
		$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$url=preg_replace("/\?.*/","",$url)."?act=add_comment";
		$content .= "
			<p><form method='POST' action='".$url."'>
				<fieldset class='postNewComment'>
					<legend>Post a comment:</legend>
					<textarea id='txtComment' name='txtComment'></textarea><br/><br/>";

		if($this->config->get('./useRecaptcha') == '1')
			$content .= recaptcha_get_html("6LdVzgYAAAAAAJo5-GBbXGu-l3OoDmfD8Hx8EojQ");
		else
			$content .= "Enter text as appears in the image below<br/>
					<img class='captcha' src=\"".Util::combinePath($G_HOME,"modules/ext/securimage/securimage_show.php?sid=".md5(uniqid(time())))."\" id=\"image\" align=\"absmiddle\" /><br/>
					<input type='text' id='txtCaptcha' name='txtCaptcha'/><br/><br/>";
		
		$content .="Email (optional, we'll keep you posted on this thread only).<br/>
					<input type='text' id='txtEmail' name='txtEmail'/><br/><br/>
					<input type='submit' value='Post my comment'></input><br/><br/>";
		if($this->_message && $this->action == "success")
			$content .= "<label class='success'>".$this->_message."</label><br/><br/>";
		else if($this->_message)
			$content .= "<label class='error'>".$this->_message."</label><br/><br/>";
		$content .= "</fieldset>
			</form></p>";
			
		if($this->_post->commentCount > 0)
		{
			$content .="<p class='postComments'>";
						
			foreach($this->_postComments as $comment)
			{
				$email = preg_replace("/@.*$/","",$comment->email);				
				$email = strlen($email) > 0 ? $email : "someone";
				
				$content .="<div class='postComment'>
							<h4>".$email." said...</h4>
							<div class='postCommentText'>".$comment->content."</div>
							<h5>".date('d/m/Y',$comment->entryDate)."</h5>";
				
				if ( isset($this->user) && $this->user->type >= 1)
				{
					$url=preg_replace("/\?.*/","",$url)."?act=del_comment&commentId=".$comment->id;
					$content .="<a href='".$url."'>delete comment</a>";
				}
				
				$content .="</div>";
			}
			
			$content .="</p>";
		}

	}
	
	function setSEODetails()
	{
		global $title;
		global $description;
		
		$title = Util::cutStringFullWords($this->config->get('./siteName')." - ".$this->_post->title,65).".";
		$description = Util::cutStringFullWords($this->config->get('./siteName').' - '.$this->_post->desc,255).".";
	}
	
	function getCategoryInfo()
	{
		$array = Feed::getTagCloud($this->oFeedItem->feedId);
		
		$categoryInfo;
		
		foreach($array as $row)
		{
			if(isset($row['tag_id']))
			{
				$categoryInfo = $row;
				break;
			}
		}
		
		return $categoryInfo;
	}
	
	function renderBreadcrumbs()
	{
		parent::renderBreadcrumbs();
/*		
		global $breadcrumbs;
		
		global $G_HOME;
		
		if( isset($this->_categoryInfo))
		{
			$parentName = $this->_categoryInfo['tag'];
			$feedUrl = Util::combinePath($G_HOME,"index.php?pg=feed_category&catId=".$this->_categoryInfo['id']."&itemId=0");
		}
		else
		{
			$parentName = $this->oFeedItem->feedName;
			$feedUrl = Util::combinePath($G_HOME,"index.php?pg=feed_source&sourceId=".$this->oFeedItem->feedId."&itemId=0");
		}

		$feedItemName = $this->oFeedItem->title;
		
		$breadcrumbs .= "&nbsp;&#187;&nbsp;<a href='$feedUrl'>$parentName</a>&nbsp;&#187;&nbsp;$feedItemName";
*/
	}
}

$renderer = new PostRenderer();

?>